package com.shxy.rlzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shxy.rlzy.entity.Menu;
import com.shxy.rlzy.entity.Role;
import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.mapper.UserMapper;
import com.shxy.rlzy.service.IMenuService;
import com.shxy.rlzy.service.IRoleService;
import com.shxy.rlzy.service.IUserRoleService;
import com.shxy.rlzy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tanhao
 * @since 2021-08-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    IRoleService roleService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IMenuService menuService;

    @Override
    public User getByUsername(String username) {
        return getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public String getUserAuthorities(Long userId) {
        String authorities = "";

        // 获取角色
        List<Role> roles = roleService.list(new QueryWrapper<Role>()
                .inSql("id", "select role_id from sys_user_role where user_id=" + userId));

        // 将角色名称进行格式转换
        if(roles.size() > 0) {
            String roleCodes = roles.stream().map(role -> "ROLE_" + role.getCode()).collect(Collectors.joining(","));
            authorities = roleCodes;
        }
        // 获取菜单操作权限
        List<Long> menuIds = userMapper.getNavManuIds(userId);
        if(menuIds.size() > 0) {
            List<Menu> menus = menuService.listByIds(menuIds);
            String menuPerms = menus.stream().map(menu -> menu.getPerms()).collect(Collectors.joining(","));

            authorities = authorities.concat(",").concat(menuPerms);
        }

        return authorities;
    }
}
